#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :   2021/5/6 17:22
@Author:  linjinting
@File: main.py
@Software: PyCharm
"""

import sys
import logging
import threading
from PySide2 import QtWidgets
from UI_tools import Ui_Form_PDF_Tools
from TTLLogging import create_logger
from baidu_aip_demo import api_getWordFromImage, api_getToken
from pdf_convert import convert_to_pdf_simple, convert_to_pdf
from separatePDF import SeparatePDF
from mergePDF import MergePDF


class UIHandle(logging.StreamHandler):
    def __init__(self, widget):
        logging.StreamHandler.__init__(self, widget)
        self.formatter = logging.Formatter(
            "[%(asctime)s] %(levelname)s in %(name)s.%(module)s at %(lineno)d: %(message)s")


class Form_PDF_Tools(QtWidgets.QFrame, Ui_Form_PDF_Tools):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.bound_single()

        self.m_logger = create_logger('pdf.tools.main')
        handle = UIHandle(self)
        self.m_logger.addHandler(handle)

    def bound_single(self):
        # separate
        self.pushButton_separate_source.clicked.connect(self.separate_getOpenFileName)
        self.pushButton_separate_destination.clicked.connect(self.separate_getExistingDirectory)
        self.pushButton_separate.clicked.connect(self.separate_pdf)
        # merge
        self.pushButton_merge_save.clicked.connect(self.merge_getSaveFileName)
        self.pushButton_merge_source.clicked.connect(self.merge_getExistingDirectory)
        self.pushButton_merge.clicked.connect(self.merge_pdf)
        # convert_image
        self.pushButton_convert_image_source_file.clicked.connect(self.convert_image_getOpenFileName)
        self.pushButton_convert_image_source_dir.clicked.connect(self.convert_image_source_getExistingDirectory)
        self.pushButton_convert_image_destination.clicked.connect(self.convert_image_getExistingDirectory)
        self.pushButton_convert_image.clicked.connect(self.convert_image)
        # convert_pdf
        self.pushButton_convert_pdf_source.clicked.connect(self.convert_pdf_getOpenFileName)
        self.pushButton_convert_pdf_source_dir.clicked.connect(self.convert_pdf_source_getExistingDirectory)
        self.pushButton_convert_pdf_destination_file.clicked.connect(self.convert_pdf_getSaveFileName)
        self.pushButton_convert_pdf_destination.clicked.connect(self.convert_pdf_getExistingDirectory)
        self.pushButton_convert_pdf.clicked.connect(self.convert_pdf)
        # convert_pdf
        self.pushButton_convert_pdf_word_source.clicked.connect(self.convert_pdf_word_getOpenFileName)
        self.pushButton_convert_pdf_word_source_dir.clicked.connect(self.convert_pdf_word_source_getExistingDirectory)
        self.pushButton_convert_pdf_word_save.clicked.connect(self.convert_pdf_word_getSaveFileName)
        self.pushButton_convert_pdf_word_save_dir.clicked.connect(self.convert_pdf_word_getExistingDirectory)
        self.pushButton_convert_pdf_word.clicked.connect(self.convert_pdf_to_word)
        self.pushButton_convert_word_pdf.clicked.connect(self.convert_word_to_pdf)
        # baidu ocr
        self.pushButton_ocr_source.clicked.connect(self.ocr_source_getOpenFileName)
        self.pushButton_get_token.clicked.connect(self.baidu_ai_get_token)
        self.pushButton_recognition.clicked.connect(self.baidu_aip_ocr)

    def separate_getOpenFileName(self):
        file_path, file_type = QtWidgets.QFileDialog.getOpenFileName(self, '选择文件', '', 'pdf(*.pdf)')
        self.lineEdit_separate_source.setText(file_path)

    def separate_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择保存路径')
        self.lineEdit_separate_destination.setText(file_path)

    def merge_getExistingDirectory(self):
        source_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择保存路径')
        self.lineEdit_merge_source_dir.setText(source_path)

    def merge_getSaveFileName(self):
        file_path, file_type = QtWidgets.QFileDialog.getSaveFileName(self, '选择保存路径', 'merge.pdf', 'pdf(*.pdf)')
        # print(file_path, file_type)
        if not file_path:
            file_path = 'merge.pdf'
        self.lineEdit_merge_save.setText(file_path)

    def convert_image_getOpenFileName(self):
        file_path, file_type = QtWidgets.QFileDialog.getOpenFileName(self, '选择文件', '', 'pdf(*.pdf)')
        self.lineEdit_convert_image_source_file.setText(file_path)
        self.lineEdit_convert_image_source_dir.setText("")

    def convert_image_source_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择文件夹')
        self.lineEdit_convert_image_source_dir.setText(file_path)
        self.lineEdit_convert_image_source_file.setText("")

    def convert_image_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择保存路径')
        self.lineEdit_convert_image_destination.setText(file_path)

    def convert_pdf_getOpenFileName(self):
        img_type = self.comboBox_convert_pdf_img_type.currentText()
        file_path, file_type = QtWidgets.QFileDialog.getOpenFileName(self, '选择文件', '',
                                                                     '%s(*.%s)' % (img_type, img_type))
        self.lineEdit_convert_pdf_source.setText(file_path)
        self.lineEdit_convert_pdf_source_dir.setText("")

    def convert_pdf_source_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择文件夹')
        self.lineEdit_convert_pdf_source_dir.setText(file_path)
        self.lineEdit_convert_pdf_source.setText("")

    def convert_pdf_getSaveFileName(self):
        file_path, file_type = QtWidgets.QFileDialog.getSaveFileName(self, '选择文件', '', 'pdf(*.pdf)')
        self.lineEdit_convert_pdf_destination_dir.setText("")
        self.lineEdit_convert_pdf_destination.setText(file_path)

    def convert_pdf_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择保存路径')
        self.lineEdit_convert_pdf_destination_dir.setText(file_path)
        self.lineEdit_convert_pdf_destination.setText("")

    def convert_pdf_word_getOpenFileName(self):
        word_type = self.comboBox_convert_pdf_word_type.currentText()
        file_path, file_type = QtWidgets.QFileDialog.getOpenFileName(self, '选择文件', '',
                                                                     '%s(*.%s)' % (word_type, word_type))
        self.lineEdit_convert_pdf_word_source.setText(file_path)
        self.lineEdit_convert_pdf_word_source_dir.setText("")

    def convert_pdf_word_source_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择文件夹')
        self.lineEdit_convert_pdf_word_source_dir.setText(file_path)
        self.lineEdit_convert_pdf_word_source.setText("")

    def convert_pdf_word_getSaveFileName(self):
        file_path, file_type = QtWidgets.QFileDialog.getSaveFileName(self, '选择文件', '', 'pdf(*.pdf)')
        self.lineEdit_convert_pdf_word_save_dir.setText("")
        self.lineEdit_convert_pdf_word_save.setText(file_path)

    def convert_pdf_word_getExistingDirectory(self):
        file_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择保存路径')
        self.lineEdit_convert_pdf_word_save_dir.setText(file_path)
        self.lineEdit_convert_pdf_word_save.setText("")

    def ocr_source_getOpenFileName(self):
        file_path, file_type = QtWidgets.QFileDialog.getOpenFileName(self, '选择文件', '', 'Image files(*.bmp *.jpg *.pbm '
                                                                                       '*.pgm *.png *.ppm *.xbm '
                                                                                       '*.xpm);;All files (*.*)')
        self.lineEdit_ocr_source.setText(file_path)

    def separate_pdf(self):
        source_file = self.lineEdit_separate_source.text()
        output_path = self.lineEdit_separate_destination.text()

        pattern = self.lineEdit_separate_pattern.text()
        if not source_file:
            self.m_logger.error("源文件为空，退出！")
            return
        if not output_path:
            self.m_logger.error("存放目录为空，退出！")
            return
        if not pattern:
            self.m_logger.error("分割方式为空，退出！")
            return
        SPDF = SeparatePDF(self.m_logger)
        th = threading.Thread(target=SPDF.run, args=[pattern, source_file, output_path])
        th.start()
        # SPDF.run(pattern, source_file, output_path)

    def merge_pdf(self):
        source_path = self.lineEdit_merge_source_dir.text()
        save_path = self.lineEdit_merge_save.text()
        if not source_path:
            self.m_logger.error("源目录路径为空，退出！")
            return
        if not save_path:
            self.m_logger.error("保存文件路径为空，退出!")
            return
        th = threading.Thread(target=MergePDF, args=[source_path, save_path, self.m_logger])
        th.start()
        # MergePDF(source_path, save_path, self.m_logger)

    def convert_image(self):
        file_path = self.lineEdit_convert_image_source_file.text()
        dir_path = self.lineEdit_convert_image_source_dir.text()
        destination_path = self.lineEdit_convert_image_destination.text()
        img_type = self.comboBox_convert_img_img_type.currentText()
        try:
            rotate = int(self.lineEdit_convert_image_rotate.text())
            zoom_x = float(self.lineEdit_convert_image_zoomX.text())
            zoom_y = float(self.lineEdit_convert_image_zoomY.text())
            alpha = int(self.lineEdit_convert_image_alpha.text())
        except Exception as e:
            self.m_logger.error(e)
            self.m_logger.error("转换参数错误，系统使用默认值！")
            rotate = 0
            zoom_x = 2.0
            zoom_y = 2.0
            alpha = 0
        kwargs = {
            "img_type": img_type,
            "rotate": rotate,
            "zoom_x": zoom_x,
            "zoom_y": zoom_y,
            "alpha": alpha,
        }
        self.m_logger.debug(kwargs)
        if not dir_path and not file_path:
            self.m_logger.error("源目录及源文件路径不能同时为空，退出！")
            return
        if not destination_path:
            self.m_logger.error("保存目录路径为空，退出!")
            return
        from pdf_convert import convert_to_image
        if not dir_path:
            source_path = file_path
        else:
            source_path = dir_path
        th = threading.Thread(target=convert_to_image,
                              args=[source_path, destination_path, self.m_logger], kwargs=kwargs)
        th.start()
        # convert_to_image(source_path, destination_path, self.m_logger, **kwargs)

    def convert_pdf(self):
        source_file_path = self.lineEdit_convert_pdf_source.text()
        source_dir_path = self.lineEdit_convert_pdf_source_dir.text()
        destination_path = self.lineEdit_convert_pdf_destination.text()
        destination_dir_path = self.lineEdit_convert_pdf_destination_dir.text()
        img_type = self.comboBox_convert_pdf_img_type.currentText()

        if source_file_path:
            source_path = source_file_path
        elif source_dir_path:
            source_path = source_dir_path
        else:
            self.m_logger.error("源文件及源目录路径不能同时为空，退出!")
            return

        if destination_path:
            th = threading.Thread(target=convert_to_pdf_simple,
                                  args=[source_path, destination_path, img_type, self.m_logger])
            th.start()
            # convert_to_pdf_simple(source_path, destination_path, img_type, self.m_logger)
        elif destination_dir_path:
            th = threading.Thread(target=convert_to_pdf,
                                  args=[source_path, destination_path, img_type, self.m_logger])
            th.start()
            # convert_to_pdf(source_path, destination_dir_path, img_type, self.m_logger)
        else:
            self.m_logger.error("保存目录及保存文件不能同时为空，退出！")
            return

    def convert_pdf_to_word(self):
        source_file_path = self.lineEdit_convert_pdf_word_source.text()
        source_dir_path = self.lineEdit_convert_pdf_word_source_dir.text()
        save_path = self.lineEdit_convert_pdf_word_save.text()
        save_dir_path = self.lineEdit_convert_pdf_word_save_dir.text()
        img_type = self.comboBox_convert_pdf_img_type.currentText()

        if source_file_path:
            source_path = source_file_path
        elif source_dir_path:
            source_path = source_dir_path
        else:
            self.m_logger.error("源文件及源目录路径不能同时为空，退出!")
            return

        if save_path:
            print(save_path)
            # th = threading.Thread(target=convert_to_pdf_simple,
            #                       args=[source_path, save_path, img_type, self.m_logger])
            # th.start()
        elif save_dir_path:
            print(save_dir_path)
            # th = threading.Thread(target=convert_to_pdf,
            #                       args=[source_path, save_dir_path, img_type, self.m_logger])
            # th.start()
        else:
            self.m_logger.error("保存目录及保存文件不能同时为空，退出！")
            return

    def convert_word_to_pdf(self):
        pass

    def baidu_ai_get_token(self):
        API_KEY = self.lineEdit_baiduAPI_API_KEY.text()
        SECRET_KEY = self.lineEdit_baiduAPI_SECRET_KEY.text()

        api_getToken(API_KEY, SECRET_KEY, self.m_logger)

    def baidu_aip_ocr(self):
        # APP_ID = '20457265'
        # API_KEY = 'VYTH0oG4XPw8wBRcIcmD02VO'
        # SECRET_KEY = 'o2IhypQcXDpPXt8lVzcyTFyuDvPMGTDG'
        # APP_ID = self.lineEdit_baiduAPI_APP_ID.text()
        # API_KEY = self.lineEdit_baiduAPI_API_KEY.text()
        # SECRET_KEY = self.lineEdit_baiduAPI_SECRET_KEY.text()
        token = self.lineEdit_baidu_orc_token.text()
        source_path = self.lineEdit_ocr_source.text()
        if not source_path:
            self.m_logger.error("源目录路径为空，退出！")
            return
        self.m_logger.info("开始识别%s上的文字" % source_path)
        self.textEdit_ocr_result.setText("")

        # self.m_logger.info("识别完成")

        th = threading.Thread(target=api_getWordFromImage, args=[source_path, token, self.ocr_callback, self.m_logger])
        th.start()
        # words = client.getWordFromImage(source_path)

    def write(self, msg):
        self.textBrowser_log.insertPlainText(msg)
        self.textBrowser_log.moveCursor(self.textBrowser_log.textCursor().End)

    def ocr_callback(self, words):
        self.m_logger.info("开始回显文字")
        # for word in words:
        #     print(word)
        word = "\n".join(words)
        self.textEdit_ocr_result.insertPlainText(word)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    form = Form_PDF_Tools()
    form.show()
    sys.exit(app.exec_())
